import yaml
from pathlib import Path

CONFIG_DIR = Path(__file__).parent
DEFAULT_CFG = CONFIG_DIR / "default.yaml"
USER_CFG = CONFIG_DIR / "user.yaml"

def load_config():
    """合并 default.yaml 和 user.yaml"""
    with open(DEFAULT_CFG, "r", encoding="utf-8") as f:
        config = yaml.safe_load(f) or {}

    if USER_CFG.exists():
        with open(USER_CFG, "r", encoding="utf-8") as f:
            user_cfg = yaml.safe_load(f) or {}
        merge_dict(config, user_cfg)

    return config

def save_user_config(cfg: dict):
    """保存 user.yaml"""
    with open(USER_CFG, "w", encoding="utf-8") as f:
        yaml.safe_dump(cfg, f, allow_unicode=True)

def merge_dict(base: dict, override: dict):
    """递归合并字典"""
    for k, v in override.items():
        if isinstance(v, dict) and isinstance(base.get(k), dict):
            merge_dict(base[k], v)
        else:
            base[k] = v
